<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '添加评价',
    backgroundColor: '#f5f5f5',
    enablePullDownRefresh: true,
  },
}
</route>

<template>
  <view class="comment-container">
    <!-- <text class="title">订单评价</text> -->

    <view v-for="(item, index) in orderItems" :key="item.id.toString" class="item-review">
      <view class="goods-info">
        <view class="img-box"><wd-img :width="50" :height="50" :src="item.imgUrl" /></view>

        <text class="item-name">{{ item.skuName }}</text>
      </view>
      <!-- 评分模块 -->
      <view class="section comment-sore">
        <text class="section-title">商品评分</text>
        <wd-rate v-model="item.score" size="16" active-color="#ff7900" />
      </view>

      <!-- 评价标签 -->
      <view class="section">
        <!-- <text class="section-title">选择评价标签</text> -->
        <view class="tag-list">
          <view
            v-for="tag in tagList"
            :key="tag.id"
            class="tag-item"
            :class="{ active: item.selectedTags.includes(tag.id) }"
            @click="toggleTag(item, tag.id)"
          >
            {{ tag.tagName }}
          </view>
        </view>
      </view>

      <!-- 文字评价 -->
      <view class="section">
        <!-- <text class="section-title">详细评价</text> -->
        <wd-textarea
          v-model="item.content"
          placeholder="请输入您的使用体验（建议200字以内）"
          :maxlength="200"
          custom-textarea-container-class="textarea"
          show-word-limit
          size="12"
          auto-height
        />
      </view>

      <!-- 图片上传 -->
      <view class="section">
        <text class="section-title">上传图片（最多6张）</text>
        <wd-upload
          :file-list="item.fileList"
          name="file"
          @success="afterUpload(item, $event)"
          image-mode="aspectFill"
          :limit="6"
          :upload-method="customUpload"
          @remove="removeImg(item, $event)"
          @change="handleUploadChange(item, $event)"
        />
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-btn-container">
      <wd-button type="primary" block @click="handleSubmit">提交评价</wd-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getTagList, addComment } from '@/service/goods/comment/comment'
import type { CommentTag, GoodsCommentDto } from '@/service/goods/comment/comment.d'
import { OrderApi } from '@/service/order/order'
import { OrderStatusEnum } from '@/service/order/orderEnum.d'
import { useToast } from 'wot-design-uni'
import { useUserStore } from '@/store/user'
const userStore = useUserStore()
const toast = useToast()
const uploadAction = import.meta.env.VITE_UPLOAD_BASEURL

// 订单项数据结构
interface OrderItem {
  id: bigint
  skuName: string
  score: number
  content: string
  selectedTags: number[]
  imgUrl: string
  goodsId: number
  fileList: any[]
}
const mode = ref<'insert' | 'readOnly'>('insert')
const orderId = ref()
onLoad((options) => {
  if (options.orderId && options.type) {
    orderId.value = options.orderId
    mode.value = options.type
  } else {
    toast.show('参数异常')
    uni.navigateBack()
  }
})
onShow(() => {
  console.log('show', orderId.value)
})

// 表单数据结构
const orderItems = ref<OrderItem[]>([])
const tagList = ref<CommentTag[]>([])

// 初始化加载标签和订单项
onMounted(async () => {
  try {
    const res = await getTagList()
    tagList.value = res.data

    // 获取订单详情
    const { code, data } = await OrderApi.getDetail(orderId.value)
    if (code === 200 && data) {
      orderItems.value = data.orderItemList.map((item) => ({
        id: item.id,
        skuName: item.skuName,
        score: 5,
        content: '',
        selectedTags: [],
        fileList: [],
        imgUrl: item.thumbImg,
        goodsId: item.goodsId,
      }))
    } else {
      toast.show('订单详情加载失败')
    }
  } catch (e) {
    console.error('加载评价标签或订单详情失败:', e)
  }
})
const customUpload = (file, formData, options) => {
  console.log(options.header)
  console.log('formData', formData)

  const uploadTask = uni.uploadFile({
    url: uploadAction,
    header: options.header,
    name: options.name,
    fileName: options.name,
    fileType: options.fileType,
    formData: { category: 'commentImg' },
    filePath: file.url,
    success(res) {
      console.log(res)

      if (res.statusCode === options.statusCode) {
        // 设置上传成功

        options.onSuccess(res, file, formData)
      } else {
        // 设置上传失败
        options.onError({ ...res, errMsg: res.errMsg || '' }, file, formData)
      }
    },
    fail(err) {
      // 设置上传失败
      options.onError(err, file, formData)
    },
  })
  // 设置当前文件加载的百分比
  uploadTask.onProgressUpdate((res) => {
    options.onProgress(res, file)
  })
}

const afterUpload = (item: OrderItem, { file, fileList, formData }) => {
  console.log('上传成功之后')
  console.log(file)
  console.log(fileList)
  console.log(formData)
  const response = JSON.parse(fileList[0].response)
  item.fileList.push(response.data)
}

const removeImg = (item: OrderItem, { file }) => {
  const response = JSON.parse(file.response)
  console.log(response.data)
  const list = item.fileList.filter((img) => {
    return img !== response.data
  })
  item.fileList = list
}

// 标签切换
const toggleTag = (item: OrderItem, tagId: number) => {
  const index = item.selectedTags.indexOf(tagId)
  if (index > -1) {
    item.selectedTags.splice(index, 1)
  } else {
    if (item.selectedTags.length < 3) {
      item.selectedTags.push(tagId)
    } else {
      uni.showToast({ title: '最多选择3个标签', icon: 'none' })
    }
  }
}

// 图片上传处理
const handleUploadChange = (item: OrderItem, { fileList: files }) => {}

// 提交评价
const handleSubmit = async () => {
  toast.loading('加载中')
  const params: GoodsCommentDto[] = orderItems.value.map((item) => ({
    score: item.score,
    content: item.content,
    goodsId: item.goodsId,
    nickname: userStore.userInfo.nickname,
    userId: userStore.userInfo.id,
    avatarUrl: userStore.userInfo.avatarUrl,
    tagNames: item.selectedTags.map((tagId) => ({
      commentTagId: tagId,
      goodsId: item.goodsId,
      userId: userStore.userInfo.id,
    })),
    contentUrl: item.fileList.join(','),
  }))
  console.log(params)

  try {
    const { code, data, message } = await addComment(params)

    if (code === 200 && data) {
      toast.close()
      uni.showToast({ title: '评价提交成功' })
      OrderApi.updateOrderStatus({ orderId: orderId.value, status: OrderStatusEnum.COMPLETED })
      setTimeout(() => uni.navigateBack(), 1500)
    } else {
      toast.close()
      toast.show(message)
    }
  } catch (e) {
    toast.close()
    console.error('提交评价失败:', e)
    toast.show('提交失败，请重试')
  }
}
</script>

<style lang="scss" scoped>
.comment-container {
  min-height: 100vh;
  padding: 24rpx;
  background-color: #f8f8f8;
}

.item-review {
  padding: 20rpx;
  margin-bottom: 32rpx;
  background: white;
  border-radius: 16rpx;
  .item-name {
    margin-left: 10rpx;
    font-size: 24rpx;
  }
  .goods-info {
    display: flex;
    .img-box {
      border: 1rpx solid #f5f5f5;
    }
  }
}
.section {
  margin-top: 10rpx;
  .textarea {
    font-size: 20rpx;
  }
}
.comment-sore {
  display: flex;
  justify-content: space-between;
}
.section-title {
  display: block;
  margin-bottom: 16rpx;
  font-size: 24rpx;
  font-weight: 500;
  color: #333;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;

  .tag-item {
    padding: 12rpx;
    font-size: 20rpx;
    color: #666;
    background: #f5f5f5;
    border-radius: 48rpx;
    transition: all 0.2s;

    &.active {
      font-weight: 500;
      color: #ff7900;
      background: #fff0e6;
    }
  }
}

.submit-btn-container {
  margin: 48rpx 24rpx;
}
</style>
